﻿using System.Collections.Generic;
using Engine;
using Game;
using Mekiasm.Common;
namespace Mekiasm
{
    public class ElectricSystem
    {

        public static List<Element<Interface.IMekPowerMachine>> Elements = new List<Element<Interface.IMekPowerMachine>>();

        public static void Add(Element<Interface.IMekPowerMachine> Element)
        {
            if (Elements.Find(p => p.Point == Element.Point) == null)
            {
                Elements.Add(Element);
                UpdateConnection(Element.Point);
            }
        }
        public static Element<Interface.IMekPowerMachine> Get(Point3 point3)
        {
            return Elements.Find(p => p.Point == point3);
        }

        public static void UpdateConnection(Point3 pointStart)
        {
            ClearFlags();
            updateConnectionsLogic(pointStart);
        }

        public static void updateConnectionsLogic(Point3 pointStart)
        {
            var StartElement = Elements.Find(p => p.Point == pointStart);
            if (StartElement == null || StartElement.Visited) return;
            StartElement.Visited = true;
            StartElement.Connections.Clear();
            for (int i = 0; i < 6; i++)
            {
                Point3 point3 = pointStart + CellFace.FaceToPoint3(i);
                var neibor = Elements.Find(p => p.Point == point3);
                if (neibor != null)
                {
                    StartElement.Connections.Add(neibor);
                }
                updateConnectionsLogic(point3);
            }
        }
        public static void ClearFlags()
        {
            for (int i = 0; i < Elements.Count; i++)
            {
                Elements[i].Visited = false;
            }
        }
        public static void Remove(Point3 point3)
        {
            var element = Elements.Find(p => p.Point == point3);
            if (element != null)
            {
                Elements.Remove(element);
                for (int i = 0; i < Elements.Count; i++)
                {
                    var element1 = Elements[i].Connections.Find(p => p.Point == point3);
                    if (element1 != null) Elements[i].Connections.Remove(element1);
                }
            }
            UpdateConnection(point3);
        }

        public static void Update(float dt)
        {
            for (int i = 0; i < Elements.Count; i++)
            {
                Elements[i].Simulate();
            }
        }
        public static void Dispose()
        {
            Elements.Clear();
        }
    }
}
